import { Button, Modal, Input, Tree, Icon, Avatar, Checkbox,message, Spin } from 'antd';
import React, {useState, useEffect} from 'react';
import { Scrollbars } from 'react-custom-scrollbars';
import styles from './ObjectOfApproval.less';
import { useRequest } from '@umijs/hooks';
import { getTreeData, handleAudit, getTreeUser, getAuditPeople } from '../../service';
import { aesEncrypt } from '@/config/cryptoService'; // 加密

const { TreeNode } = Tree;
import AvatorPhoto from './images/default-avatar-man.png';

let arr = []
const ObjectOfApproval = props => {

  const { approvalData, approvalVisible, handleApprovalVisible, onSuccess } = props;

  const [current, setCurrent] = useState(1);
  const [keySearch, setKeySearch] = useState('');

  // 列表数据
  const [listData, handleListData] = useState([])

  // 人员列表---选择的人员数据
  const[selectedItemIds, setSelectedItemIds] = useState([])
  const[selectedItems, setSelectedItems] = useState([])

  //搜索框loading
  const [loadingSearch, handleLoadingSearch] = useState(false)
  const [showList, handleShowList] = useState(true); // 是否展示列表
  const [btnLoading, handleBtnLoading] = useState(false)
 
  const [loading, handleLoading] = useState(true) // 列表加载
	const [upLoading, handleUpLoading] = useState('') // 上滑加载

  const {run} = useRequest((params) => getAuditPeople(params), {
    manual: true,
    onSuccess: res => {
      handleLoading(false)
      
      const _listData = [...listData, ...res.data]

      handleLoadingSearch(false)

      res.data.length === 0 ? handleUpLoading(false) : handleUpLoading('')

      handleListData(_listData)
    },
    onError: err => {
      console.log(err);
      handleLoadingSearch(false)
    }
  })

  useEffect(() => {
    if (approvalVisible) {
      run({
        pageSize: 20,
        current,
        keySearch,
        roleName: approvalData.roleName
      })
    }
  }, [approvalVisible, current, keySearch, run])

  // 搜索
  const searchVal = (value, event) => {
    handleLoadingSearch(true)
    handleListData([])
    setCurrent(1)
    setKeySearch(value)
  }

  const loadMore = () => {
    if (upLoading !== false) {
			handleUpLoading(true)
			setCurrent(pre => pre + 1);
		}
  }

  // 点击左侧列表
  const changeItem = val => {
    // if (val.userId === localStorage.getItem('userId')) {
    //   message.error("下一级审核人不能选择当前登录人")
    //   return false
    // }
    if (!~selectedItemIds.indexOf(val.userId)){
      // setSelectedItemIds(pre => pre.concat([val.userId]))
      // setSelectedItems(pre => pre.concat([val]))
      setSelectedItemIds(pre => [val.userId].concat(pre))
      setSelectedItems(pre => [val].concat(pre))
    } else {
      setSelectedItemIds(pre => pre.filter(userId => userId !== val.userId))
      setSelectedItems(pre => pre.filter(item => item.userId !== val.userId))
    }
  }
  // 点击右侧已选列表
  const closeItem = (id) => {

    setSelectedItemIds(pre => pre.filter(userId => userId !== id))
    setSelectedItems(pre => pre.filter(item => item.userId !== id))
  }

  const sureDept = () => {
    if (selectedItemIds.length === 0) {
      message.error("请选择审核人员")
    } else {
      const hide = message.loading('正在提交')
      handleBtnLoading(true)
      let arr = selectedItemIds.join(',')
      // const encryptParams = JSON.parse(JSON.stringify(arr));
      console.log(arr);

      // 加密
      // let encryptParams1 = aesEncrypt(encryptParams);

      handleAudit({...approvalData, handleUser:arr}).then(res=>{
        onSuccess(res)
        hide()
        handleBtnLoading(false)
        closeModal()
      }).catch(err =>{
        hide()
        handleBtnLoading(false)
      })
    }
  }
  // 关闭弹框
  const closeModal = () => {
    handleApprovalVisible(false)
    setCurrent(1)
    setSelectedItemIds([])
    setSelectedItems([])
    handleListData([])
    setKeySearch('')
  }
  return (
      <Modal
        destroyOnClose={true}
        wrapClassName={styles.approvalObject}
        onCancel={closeModal}
        footer={null}
        width={618}
        title='选择审批对象'
        visible={approvalVisible}
      >
        <div className={styles.leftCantainer}>
          <div className={styles.left}>
            <div className={styles.searchBox}>
              <Input.Search  placeholder="搜索姓名/工号" 
                loading={loadingSearch}
                allowClear={true}
                onSearch={(value, event)=>{
                  searchVal(value, event)
                }}
                enterButton />
            </div>
            <div className={styles.content}>
              <Scrollbars onScrollStop={()=>{loadMore()}} autoHide style={{height: "100%", width: "100%"}}>
                  {listData.length>0 && listData.map(v=>{
                    return (
                      <div onClick={() => changeItem(v)} key={v.userId} style={{paddingTop: '10px'}} className={styles.item}>
                        <span className={styles.avatar}>
                          {/* <Avatar
                            shape="avatar"
                            src={v.photo ? v.photo : Photo}
                          /> */}
                          {
                            v.photo
                            ? <Avatar style={{ width: '100%', height: '100%' }} src={`data:image/png;base64,${v.photo}`} />
                            : <Avatar style={{ width: '100%', height: '100%', fontSize: '80px' }} size={64} src={AvatorPhoto} />
                          }
                          <span className={`${styles.dutyCircle} ${v && v.isOnDuty === '1' ? styles.active : '' } `}></span>
                        </span>
                        <div className={styles.personInfo}>
                          <span>{v.userName}</span>
                          <span>{v.department}</span>
                        </div>
                        <div className={styles.itemCheck}>
                          <span className={` ${~selectedItemIds.indexOf(v.userId)  ? styles.active : ''}`}>
                            {~selectedItemIds.indexOf(v.userId) ? <Icon type="check" /> : null}
                          </span>
                        </div>
                      </div>
                    )
                  })}
                  <div style={{textAlign: 'center', padding: '20px 0'}}>
                    {upLoading === true ? '加载中' : ''}
                    {upLoading === false ? '已加载全部': ''}
                  </div>
                </Scrollbars>
            </div>
          </div>

          <div className={styles.right}>
            <div className={styles.rightTitle}>已选择对象</div>
            <div className={styles.content}>
              <Scrollbars autoHide style={{height: "100%", width: "100%"}}>
                {selectedItems.map(v=>{
                  return (
                    <div key={v.userId} style={{paddingTop: '10px'}} className={styles.item}>
                      <span className={styles.avatar}>
                      <Avatar
                        shape="avatar"
                        icon={v.photo ? false : 'user'}
                        src={v.photo ? v.photo : false}
                      />
                      </span>
                      <div className={styles.personInfo}>
                      <span>{v.userName}</span>
                      <span>{v.department}</span>
                      </div>
                      <span onClick={() => {closeItem(v.userId)}} style={{cursor: 'pointer'}} className={styles.checkT}>
                        <Icon type="close-circle" />
                      </span>
                    </div>
                  )
                })}
              </Scrollbars>
            </div>
          </div>
        </div>
        <div style={{textAlign: "right", padding: "10px 10px"}}>
          <Button onClick={closeModal} loading={btnLoading}>关闭</Button>
          &nbsp;&nbsp;
          <Button onClick={()=>{sureDept()}} type="primary" loading={btnLoading}>确定</Button>
        </div>
      </Modal>
  )
}

export default ObjectOfApproval;
